
package SSF.OS.TCP;


/** This class recycles SendItems and tcpMessages */
class tcpMessagePool {

  public static final int DEFAULT_MIN_POOL_SIZE = 4;
  public static final int DEFAULT_MAX_POOL_SIZE = 64;


  public tcpMessagePool() {
   this(DEFAULT_MIN_POOL_SIZE, DEFAULT_MAX_POOL_SIZE);
  }

  public tcpMessagePool(int min, int max) {
    sendItems = new SendItem[sendItemCapacity = min];
    sendItemCurrent = 0;
    limit = max;
  }

  // SendQueue will request up to TCP_BUFFER_SPACE/MSS = tcpinit.SendBufferSize
  // SendItems all at once. This does not help the pool...
  public SendItem getSendItem() {
     outSI++;
     if(sendItemCurrent==0)
       return new SendItem();
     else
       return sendItems[--sendItemCurrent];
  }

  public void recycleSendItem(SendItem obj) {
    if (sendItemCurrent == sendItemCapacity) {
      if (sendItemCapacity >= limit) return; // overflow
      SendItem[] newsendItems = new SendItem[Math.min(limit,sendItemCapacity*2)];
      System.arraycopy(sendItems,0,newsendItems,0,sendItemCapacity);
      for (int n=0; n<sendItemCapacity; n++) sendItems[n] = null;
      sendItems = newsendItems;
      sendItemCapacity = sendItems.length;
    }
    obj.clear();
    sendItems[sendItemCurrent++] = obj;
    inSI++;
    System.out.println("SendItemPool: "+inSI+" IN, "+outSI+" OUT, pool= "+sendItemCurrent);
  }

  private int sendItemCurrent, sendItemCapacity, limit;
  private int inSI, outSI;
  private SendItem[] sendItems;


}